package com.chao.stucture.list;

/**
 * @author : Rookie
 * @description :
 * @date : 2023/7/5
 */
public class FlipSingleList {

    public static void main(String[] args) {
        int[] arr = new int[]{1,2,3,4,5};
        Node head = new Node(arr[0]);
        Node curr = head;
        for (int i = 1; i < arr.length; i++) {
            curr.next = new Node(arr[i]);
            curr = curr.next;
        }
        printList(head);
        head = flipByCycle(head);
        printList(head);
        head = flipByRecurse(null,head);
        printList(head);
    }

    private static Node flipByCycle(Node head) {
        Node curr = head;
        Node prev = null;
        Node temp = null;
        while (curr != null) {
            // 记录下个节点
            temp = curr.next;
            // 将当前节点指向前一节点
            curr.next = prev;
            // 移动前一节点指针
            prev = curr;
            // 移动当前节点指针
            curr = temp;
        }
        // 返回新的头节点
        return prev;
    }

    /**
     * *=递归实现
     * @param prev 前一节点
     * @param curr 当前节点
     * @return
     */
    private static Node flipByRecurse(Node prev,Node curr) {
        if (curr == null) {
            return prev;
        }
        // 记录下个节点
        Node temp = curr.next;
        // 将当前节点指向上一节点
        curr.next = prev;
        // 移动prev指针
        prev = curr;
        // 移动curr指针
        curr = temp;
        // 翻转下个节点
        return flipByRecurse(prev,curr);
    }

    private static void printList(Node head) {
        Node curr = head;
        StringBuilder sb = new StringBuilder();
        while (curr != null) {
            sb.append(curr.val);
            if (curr.next != null) {
                sb.append("->");
            }
            curr= curr.next;
        }
        System.out.println(sb);
    }

    static class Node {
        private int val;
        private Node next;

        public Node(int val) {
            this.val = val;
        }
    }
}
